package com.itsc.action;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.alibaba.fastjson.JSON;
import com.itsc.entities.Product;
import com.itsc.entities.ProductType;
import com.itsc.service.inter.IProductService;
import com.itsc.service.inter.IProductTypeService;
import com.itsc.util.HttpUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;

public class ProductAction implements ModelDriven<Product> {

	private static final String PATHURL = "./uploadProductImages";
	Product model = new Product();
	private IProductService productService;
	private IProductTypeService productTypeService;
	private Integer id;
	private Integer parent;
	private List<Integer> check_id;
	private Integer protype_id;
	
	private Integer checkPro_id;
	

	// 文件上传属性
	private File upload;// 具体上传文件的 引用 , 指向临时目录中的临时文件
	private String uploadFileName;// 上传文件的名字,FileName 固定的写法
	private String uploadContentType;// 上传文件的类型， ContentType 固定的写法

	
	public Integer getCheckPro_id() {
		return checkPro_id;
	}

	public void setCheckPro_id(Integer checkPro_id) {
		this.checkPro_id = checkPro_id;
	}

	public List<Integer> getCheck_id() {
		return check_id;
	}

	public void setCheck_id(List<Integer> check_id) {
		this.check_id = check_id;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public void setProductTypeService(IProductTypeService productTypeService) {
		this.productTypeService = productTypeService;
	}

	public Integer getParent() {
		return parent;
	}

	public void setParent(Integer parent) {
		this.parent = parent;
	}

	public Integer getProtype_id() {
		return protype_id;
	}

	public void setProtype_id(Integer protype_id) {
		this.protype_id = protype_id;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}
	public void setProductService(IProductService productService) {
		this.productService = productService;
	}

	@Override
	public Product getModel() {
		// TODO Auto-generated method stub
		return model;
	}
	
	

	public String list() throws Exception {
		List<Product> productList = productService.selectAll();
		ActionContext.getContext().put("productList", productList);

		return "list";

	}

	public String addModel() throws Exception {

		List<ProductType> ptList = productTypeService.selectByNull();
		ActionContext.getContext().put("ptList", ptList);

		return "insert";
	}

	public String checkType() throws Exception {

		List<ProductType> ptList = productTypeService.ptList(id);

		if (ptList != null) {
			for (int i = 0; i < ptList.size(); i++) {
				ptList.get(i).setProSet(null);
				ptList.get(i).setProType(null);
				ptList.get(i).setProTypeSet(null);
			}
			String js = JSON.toJSONString(ptList, true);
			System.out.println(js);
			HttpUtil.rendText(js);
		} else {
			ServletActionContext.getResponse().getWriter().print("0");
		}

		return null;
	}

	public String add() throws Exception {

		
		ProductType pt = null;
		if (protype_id == null) {
			pt = productTypeService.selectById(parent);
		} else {
			pt = productTypeService.selectById(protype_id);
			protype_id = null;
		}
		//获取当前时间
		Date date = new Date();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String time = format.format(date);
		Date datetime = format.parse(time);
		
		//上传图片，并且修改原图片名称
		int i=uploadFileName.lastIndexOf(".");//原名称里倒数第一个"."在哪里 
		String ext=uploadFileName.substring(i);//取得后缀，及"."后面的字符
		
		String uploadName = UUID.randomUUID().toString()+ext;
		//根据服务器的文件保存地址和原文件名创建目录文件全路径
        String path = ServletActionContext.getServletContext().getRealPath("/uploadProductImages");
		//生成上传的File对象
        File targetFile = new File(path,uploadName);
        
        //复制File对象，从而实现上传文件
        FileUtils.copyFile(upload, targetFile);

		model.setProType(pt);
		model.setPro_url(PATHURL+"/"+uploadName);
		model.setPro_time(datetime);
		
		Set<Product> proSet = new HashSet<Product>();
		proSet.add(model);

		productService.save(model);

		return "ok";
	}
	
	public String show() throws Exception{
		Product product = productService.selectById(model.getPro_id());
		ActionContext.getContext().getValueStack().push(product);
		
		return "show";
	}
	
	public String delete() throws Exception{
		productService.delete(model);
		return "ok";
	}
	
	public String moredelete() throws Exception{
		for(Integer id : check_id){
			Product product = productService.selectById(id);
			productService.delete(product);
		}
		
		return "ok";
	}
	
	public String edit() throws Exception{
		Product product = productService.selectById(model.getPro_id());
		List<ProductType> ptList = productTypeService.selectByNull();
		ActionContext.getContext().put("product", product);
		ActionContext.getContext().put("ptList", ptList);
		return "edit";
	}
	
	public String update() throws Exception {
		//获取当前时间
		Date date = new Date();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String time = format.format(date);
		Date datetime = format.parse(time);
		
		ProductType pt = null;
		if (protype_id == null) {
			pt = productTypeService.selectById(parent);
		} else {
			pt = productTypeService.selectById(protype_id);
			protype_id = null;
		}
		Product pro = productService.selectById(model.getPro_id());
		model.setPro_time(datetime);
		model.setProType(pt);
		if (upload != null) {
			//上传图片，并且修改原图片名称
			int i=uploadFileName.lastIndexOf(".");//原名称里倒数第一个"."在哪里 
			String ext=uploadFileName.substring(i);//取得后缀，及"."后面的字符
			
			String uploadName = UUID.randomUUID().toString()+ext;
			//根据服务器的文件保存地址和原文件名创建目录文件全路径
	        String path = ServletActionContext.getServletContext().getRealPath("/uploadProductImages");
			//生成上传的File对象
	        File targetFile = new File(path,uploadName);
	        
	        //复制File对象，从而实现上传文件
	        FileUtils.copyFile(upload, targetFile);
	        model.setPro_url(PATHURL+"/"+uploadName);
		} else {
			model.setPro_url(pro.getPro_url());
		}
		productService.update(model);
		return "ok";
	}
	
	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkProduct() throws Exception{
		Integer productId = productService.checkProByName(model.getPro_name());
		Boolean flag = productService.checkByName(model.getPro_name());
		
		if(flag){
			ServletActionContext.getResponse().getWriter().print("1");
		}else{
			if(productId==model.getPro_id()){
				ServletActionContext.getResponse().getWriter().print("1");
			}else{
				ServletActionContext.getResponse().getWriter().print("0");
			}
		}
		
		return null;
	}
	
	public String checkpro() throws Exception{
		Boolean flag = productService.checkByName(model.getPro_name());
		if (flag) {
			ServletActionContext.getResponse().getWriter().print("1");
		} else {
			
			ServletActionContext.getResponse().getWriter().print("0");
		}
		return null;
	}
}
